<template>
  <div class="role-list">
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>角色列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddRole">新增角色</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="roleList" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column prop="updatedAt" label="更新时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.id === 1"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionTreeData"
            show-checkbox
            node-key="id"
            :default-checked-keys="roleForm.permissions"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRole" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoleStore } from '@/stores'

// 使用角色store
const roleStore = useRoleStore()

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 角色列表（从store中获取）
const roleList = computed(() => roleStore.roleList)
const loading = computed(() => roleStore.loading)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const roleFormRef = ref()
const permissionTreeRef = ref()

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  description: '',
  permissions: []
})

// 角色表单验证规则
const roleFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  permissions: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ]
}

// 权限树数据（从store中获取）
const permissionTreeData = computed(() => roleStore.permissionList)

// 树形控件属性
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 获取角色列表
const fetchRoleList = async () => {
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    name: searchForm.name
  }
  
  try {
    await roleStore.fetchRoleList(params)
    pagination.total = roleStore.total
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    await roleStore.fetchPermissionList()
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRoleList()
}

// 处理重置
const handleReset = () => {
  searchForm.name = ''
  pagination.currentPage = 1
  fetchRoleList()
}

// 处理新增角色
const handleAddRole = () => {
  dialogTitle.value = '新增角色'
  isEdit.value = false
  dialogVisible.value = true
  
  // 重置表单
  Object.assign(roleForm, {
    id: null,
    name: '',
    description: '',
    permissions: []
  })
  
  // 清空树形控件选中项
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys([])
  }
}

// 处理查看角色
const handleView = (row) => {
  dialogTitle.value = '查看角色'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(roleForm, row)
  
  // 设置树形控件选中项
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys(row.permissions)
  }
}

// 处理编辑角色
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(roleForm, row)
  
  // 设置树形控件选中项
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys(row.permissions)
  }
}

// 处理删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除角色 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await roleStore.deleteRole(row.id)
      ElMessage.success('删除成功')
      fetchRoleList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 处理保存角色
const handleSaveRole = () => {
  if (!roleFormRef.value) return
  
  roleFormRef.value.validate(async (valid) => {
    if (valid) {
      // 获取选中的权限
      if (permissionTreeRef.value) {
        roleForm.permissions = permissionTreeRef.value.getCheckedKeys()
      }
      
      saveLoading.value = true
      
      try {
        if (isEdit.value) {
          await roleStore.updateRole(roleForm.id, roleForm)
          ElMessage.success('更新成功')
        } else {
          await roleStore.createRole(roleForm)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchRoleList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchRoleList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchRoleList()
}

// 组件挂载后获取角色列表和权限列表
onMounted(() => {
  fetchRoleList()
  fetchPermissionList()
})
</script>

<style lang="scss" scoped>
.role-list {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>